package spring.framework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import spring.framework.beans.BeansException;
import spring.framework.beans.PropertyValue;
import spring.framework.beans.PropertyValues;
import spring.framework.beans.factory.config.BeanDefinition;
import spring.framework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @author pengzh
 * @class AbstractAutowireCapableBeanFactory
 * @since 2021-09-23
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibInstantiationStrategy();

    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            //创建bean
            bean = createBeanInstance(beanName, beanDefinition, args);
            //填充属性
            applyPropertyValues(bean, beanName, beanDefinition);
        } catch (BeansException e) {
            throw new BeansException("Instantiation of bean failed:", e);
        }
        addSingleton(beanName, bean);
        return bean;
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName);

    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Constructor<?>[] constructors = beanDefinition.getBeanClass().getConstructors();
        Constructor targetConstructor = null;
        for (Constructor constructor : constructors) {
            if (null != args && constructor.getParameterTypes().length == args.length) {
                targetConstructor = constructor;
            }
        }
        return getInstantiationStrategy().instantiate(beanName, beanDefinition, targetConstructor, args);
    }

    private void applyPropertyValues(Object bean, String beanName, BeanDefinition beanDefinition) throws BeansException {
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        for (PropertyValue property : propertyValues.getPropertyValues()) {
            String name = property.getName();
            Object value = property.getValue();
            if (value instanceof BeanReference) {
                //对象依赖
                BeanReference beanReference = (BeanReference) value;
                value = getBean(beanReference.getBeanName());
            }
            //属性填充
            BeanUtil.setFieldValue(bean, name, value);
        }
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }
}
